/*
 * Created by Asnull.
 * Website:https://lipux.cn/
 * Date:2023-1-28
 */

// 依赖模块
const config = require('../config');
const fs = require('fs');
const path = require("path")
const OSS = require('ali-oss');
const mysql = require('mysql');
const dayjs = require('dayjs');


// 初始化阿里云对象存储
const client = new OSS(config.aliyunOSS);

// 连接到数据库
const database = mysql.createPool(config.mysql);

// 上传文件
module.exports.uploadFile = async (req,res)=>{
    if (!req.file){
        console.log(req)
        return res.send({
            code:400,
            msg:'不支持的文件类型或文件为空！',
        })
    }else {
        let userid = req.query.user;
        try {
            const result = await client.put(req.file.filename, path.normalize(req.file.destination + '/' + req.file.filename),
                { 'x-oss-object-acl': 'public-read',}
            );
            if (result.res.status === 200){
                let date = dayjs().format('YYYY-MM-DD HH:mm:ss');
                // 插入到数据库
                console.log(req.file)
                let sql = `insert into file (filename,size,date,url,user) values (?,?,?,?,?)`;
                console.log(sql)
                database.query(sql,[req.file.originalname,req.file.size,date,result.url,userid],(err,res1)=>{
                    if(err) return res.send({
                        code:400,
                        msg:'数据库炸啦！'
                    })
                    if (res1.affectedRows === 1){
                        fs.unlinkSync(req.file.destination + '/' + req.file.filename);
                        return res.send({
                            code:200,
                            url:result.url
                        })
                    }
                })

            }
        } catch (e) {
            res.send(e)
        }
    }
    // res.send(req.file)
}

// 错误捕获中间件
module.exports.errUploadFile = (err,req,res,next) => {
    if (err.code === 'LIMIT_FILE_SIZE'){
        return res.send({
            code:400,
            msg:'上传的文件太大啦，暂不支持！'
        })
    }
}
